package top.codedance.iotp.server.net.handle.subhandle.controller.http;

import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.constent.Command;
import top.codedance.iotp.common.entity.CommonEntity;
import top.codedance.iotp.server.ServerApplication;
import top.codedance.iotp.server.net.TcpServer;
import top.codedance.iotp.server.net.handle.WsReceiveHandler;
import top.codedance.iotp.server.net.session.Session;

import java.nio.charset.StandardCharsets;

public abstract class AbsractWsReceiveHandler implements WsReceiveHandler {
    public abstract void receive(String deviceId, String clientId, Integer instance, String data);

    /**
     * 释放已经关闭的websocket服务
     * @param clientId
     */
    protected void releaseClosedWsService(String deviceId, String clientId, Integer instance, short command){
        JSONObject outputJo = new JSONObject();
        outputJo.put("clientId", clientId);
        outputJo.put("instance", instance);
        outputJo.put("release", true);
        CommonEntity commonEntity2 = new CommonEntity(ServerApplication.getDataVersion());
        commonEntity2.setCommand(command);
        commonEntity2.setBody(outputJo.toJSONString().getBytes(StandardCharsets.UTF_8));
        Session session = TcpServer.sessionManager.getSessionByDeviceId(deviceId);
        session.getChannel().writeAndFlush(commonEntity2.build());
    }
}
